package com.shenma2009.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenma2009.domain.ResultResponse;
import com.shenma2009.pojo.TbProductType;
import com.shenma2009.service.TbProductTypeService;
import com.shenma2009.mapper.TbProductTypeMapper;
import com.shenma2009.vo.TbProductTypeVo;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 33509
* @description 针对表【tb_product_type(产品分类表)】的数据库操作Service实现
* @createDate 2023-04-21 15:08:28
*/
@Service
public class TbProductTypeServiceImpl extends ServiceImpl<TbProductTypeMapper, TbProductType>
    implements TbProductTypeService{

    @Override
    public ResultResponse getTree() {
        //--1 获取所有数据
        List<TbProductType> list = this.list();

        //--2 获取所有的根节点
        List<TbProductTypeVo> collect = list.stream().filter(item -> {
            return item.getTypePid().equals(0);
        }).map(item -> {
            TbProductTypeVo tbProductTypeVo = new TbProductTypeVo();
            tbProductTypeVo.setLabel(item.getTypeName());
            tbProductTypeVo.setValue(item.getTypeId());

            // 递归查询方法
            getSubTree(list, tbProductTypeVo);

            // 返回数据
            return tbProductTypeVo;
        }).collect(Collectors.toList());


        return ResultResponse.SUCCESS(collect);
    }

    private int getSubTree(List<TbProductType> listAll, TbProductTypeVo tbProductTypeVo) {
        List<TbProductTypeVo> collect = listAll.stream().filter(item -> {
            return item.getTypePid().equals(tbProductTypeVo.getValue());
        }).map(item -> {

            TbProductTypeVo typeVo = new TbProductTypeVo();
            typeVo.setLabel(item.getTypeName());
            typeVo.setValue(item.getTypeId());

            // 递归查询方法
            getSubTree(listAll, typeVo);

            // 返回数据
            return typeVo;
        }).collect(Collectors.toList());

//        tbProductTypeVo.setChildren(collect);
        if(collect.size() > 0) {
            tbProductTypeVo.setChildren(collect);
        }
        else {
            tbProductTypeVo.setChildren(null);
        }


        return collect.size();
    }
}




